﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using System.Text;
using LINQPad;
using Xtensive.Orm;

namespace LINQPadDriver
{
  class DataContextHack : DataContextBase
  {
    private Dictionary<Entity, GridWrapper> entities = new Dictionary<Entity, GridWrapper>();
    public DataContextHack()
      : base("")
    {
    }

    public override void SubmitChanges(ConflictMode failureMode)
    {
      var changeSet = GetChangeSet();
      foreach (GridWrapper update in changeSet.Updates) {
        update.Save();
      }
      foreach (GridWrapper delete in changeSet.Deletes) {
        delete.Delete();
      }
      foreach (GridWrapper insert in changeSet.Inserts)
      {
        insert.Insert();
      }
      Session.Demand().SaveChanges();
    }

    public T Attach<T>(Entity entity) where T : GridWrapper, new()
    {
      if (entity==null)
        return null;
      GridWrapper value;
      if (entities.TryGetValue(entity, out value))
        return (T) value;
      var result = new T { Entity = entity };
      var result1 = new T { Entity = entity };
      GetTable<T>().Attach(result, result1);
      entities[entity] = result;
      return result;
    }
  }
}
